import json
import time
from pynput.mouse import Controller as MouseController, Button as MouseButton
from pynput.keyboard import Controller as KeyboardController, Key, Listener as KeyboardListener

fileName = input("[HoopyGame]:输入录制文件名后回车开始复现:")

# 加载记录的事件
with open("./"+fileName+".json", "r") as f:
    events = json.load(f)

# 初始化鼠标和键盘控制器
mouse = MouseController()
keyboard = KeyboardController()

# 标志位，用于控制是否停止复现
stop_replay = False

# 监听键盘事件
def on_press(key):
    global stop_replay
    if key == Key.esc:  # 按下 Esc 键
        stop_replay = True
        return False  # 停止监听

# 启动键盘监听器
keyboard_listener = KeyboardListener(on_press=on_press)
keyboard_listener.start()

# 复现事件
start_time = events[0]["time"]
for event in events:
    if stop_replay:
        print("复现已停止")
        break

    # 计算事件的时间间隔
    time_diff = event["time"] - start_time
    if time_diff > 0:  # 只处理正数的时间差
        time.sleep(time_diff)
    start_time = event["time"]

    # 处理鼠标移动事件
    if event["type"] == "mouse_move":
        mouse.position = (event["x"], event["y"])

    # 处理鼠标按下事件
    elif event["type"] == "mouse_press":
        mouse.position = (event["x"], event["y"])
        if event["button"] == "Button.left":
            mouse.press(MouseButton.left)
        elif event["button"] == "Button.right":
            mouse.press(MouseButton.right)

    # 处理鼠标释放事件
    elif event["type"] == "mouse_release":
        mouse.position = (event["x"], event["y"])
        if event["button"] == "Button.left":
            mouse.release(MouseButton.left)
        elif event["button"] == "Button.right":
            mouse.release(MouseButton.right)

    # 处理鼠标拖拽事件
    elif event["type"] == "mouse_drag":
        mouse.position = (event["x"], event["y"])

    # 处理键盘按键事件
    elif event["type"] == "key_press":
        key = event["key"]
        duration = event.get("duration", 0)  # 获取按键持续时间，默认为 0
        if key.startswith("Key."):
            # 处理特殊键（如 Shift、Ctrl 等）
            key = getattr(Key, key[4:])
        else:
            # 处理普通键
            key = key
        keyboard.press(key)
        time.sleep(duration)  # 模拟按键长按
        keyboard.release(key)

# 停止键盘监听器
keyboard_listener.stop()

if not stop_replay:
    print("[HoopyGame]:操作复现完成!")